const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

function formatTime(date) {
  const y = date.getFullYear();
  const m = ('0' + (date.getMonth() + 1)).slice(-2);
  const d = ('0' + date.getDate()).slice(-2);
  const h = ('0' + date.getHours()).slice(-2);
  const min = ('0' + date.getMinutes()).slice(-2);
  return `${y}-${m}-${d} ${h}:${min}`;
}

const db = cloud.database()
const userCollection = db.collection('user_info')

// 云函数入口函数
exports.main = async (event, context) => {
  // 这里改成从参数拿openid，而不是云上下文获取
  const openid = event.openid
  if (!openid) {
    return { success: false, message: '缺少openid参数' }
  }

  switch(event.action) {
    case 'getUser':
      {
        const res = await userCollection.where({ openid }).get()
        if (res.data.length > 0) {
          return { success: true, user: res.data[0] }
        } else {
          return { success: false, message: '用户不存在' }
        }
      }
    case 'createUser':
      {
        // event.userData 是客户端传来的用户数据，不包含 openid
        const userData = event.userData
        if (!userData) {
          return { success: false, message: '缺少用户数据' }
        }
        // 把字符串重新转换成 Date
        if (typeof userData.lastCheckinDate === 'string') {
          userData.lastCheckinDate = new Date(userData.lastCheckinDate);
        }
        if (typeof userData.firstCheckinDate === 'string') {
          userData.firstCheckinDate = new Date(userData.firstCheckinDate);
        }
        console.log("userData:",userData);
        // 显式写入 openid
        const res = await userCollection.add({ data: { ...userData, openid } })
        return { success: true, id: res._id }
      }
    case 'updateUser':
      {
        const updateData = event.updateData
        if (!updateData) {
          return { success: false, message: '缺少更新数据' }
        }
        // 把字符串重新转换成 Date
        if (typeof updateData.lastCheckinDate === 'string') {
          updateData.lastCheckinDate = new Date(updateData.lastCheckinDate);
        }
        if (typeof updateData.firstCheckinDate === 'string') {
          updateData.firstCheckinDate = new Date(updateData.firstCheckinDate);
        }
        console.log("updateData:",updateData);
        // 显式写入 openid（避免丢失）
        updateData.openid = openid
        // 更新匹配该 openid 的第一条用户记录
        const res = await userCollection.where({ openid }).update({ data: updateData })
        return { success: true, stats: res.stats }
      }
      case 'getDeadUsers': {
        const { page = 1, pageSize = 10 } = event;
        const now = new Date();
        const DEAD_THRESHOLD = 3;
        const cutoffDate = new Date(now.getTime() - DEAD_THRESHOLD * 24 * 60 * 60 * 1000);
      
        // 获取所有符合死亡条件的用户（分页）
        const userRes = await userCollection
          .where({ lastCheckinDate: db.command.lt(cutoffDate) })
          .orderBy('lastCheckinDate', 'asc') // 越早未打卡越靠前
          .skip((page - 1) * pageSize)
          .limit(pageSize)
          .get();
      
        const deadUsers = userRes.data;
        if (deadUsers.length === 0) {
          return {
            success: true,
            deadUsers: [],
            total: 0,
          };
        }
      
        const deadOpenIds = deadUsers.map(user => user.openid);
      
        // 查询对应留言（正序排列）
        const commentRes = await db.collection('eulogie_info')
          .where({ deadOpenId: db.command.in(deadOpenIds) })
          .orderBy('createTime', 'asc') // 💡 正序排列，最新在下方
          .get();
      
        const commentMap = {};
        for (const comment of commentRes.data) {
          const targetId = comment.deadOpenId;
          if (!commentMap[targetId]) {
            commentMap[targetId] = [];
          }
          commentMap[targetId].push({
            nickName: '匿名用户', // 后期可补 commenterOpenId 的昵称解析
            content: comment.content,
            id: comment._id,
            commenterOpenId: comment.commenterOpenId,
            time: formatTime(new Date(comment.createTime))
          });
        }
      
        // 合并用户和对应留言
        const result = deadUsers.map(user => ({
          ...user,
          commentList: commentMap[user.openid] || []
        }));
      
        return {
          success: true,
          deadUsers: result,
          total: result.length
        };
      }

      case 'incenseBatch': {
        const targetOpenId = event.targetId;
        const count = event.count;
        if (!targetOpenId || !count || count <= 0) {
          return { success: false, message: '缺少参数或计数无效' };
        }
      
        const res = await userCollection.where({ openid: targetOpenId })
          .update({
            data: {
              incenseCount: db.command.inc(count)
            }
          });
      
        if (res.stats.updated === 0) {
          return { success: false, message: '目标用户不存在或更新失败' };
        }
        return { success: true };
      }

      case 'getSummaryStats': {
        const now = new Date();
        const DEAD_THRESHOLD = 3;
        const cutoffDate = new Date(now.getTime() - DEAD_THRESHOLD * 24 * 60 * 60 * 1000);

        // 获取所有死亡用户
        const res = await userCollection
          .where({ lastCheckinDate: db.command.lt(cutoffDate) })
          .get();

        const totalUsers = res.data.length;
        const totalIncense = res.data.reduce((sum, user) => {
          return sum + (user.incenseCount || 0);
        }, 0);

        return {
          success: true,
          totalUsers,
          totalIncense
        };
      }
      
    default:
      return { success: false, message: '无效的操作类型' }
  }
}
